
/**
 * AppleIIGo
 * SDL main
 * (C) 2007-2008 by Marc S. Ressl (mressl@umich.edu)
 * Released under the GPL
 */

#import "SDL/SDL.h"

#import "SDLMain.h"
#import "Controller.h"

void copyArguments(int argc, char **argv) {
	int i;
	
	sdlArgV = (char **) SDL_malloc(sizeof(char *) * (argc + 1));
	for (i = 0; i <= argc; i++)
		sdlArgV[i] = argv[i];
	sdlArgV[argc + 1] = NULL;
	
	sdlArgC = argc;
}

int insertArgument(char *arg, int pos) {
	char *newArg;
	char **newArgV;
	int i;
	
	if ((pos < 0) || (pos > sdlArgC))
		return NO;
	
	newArg = (char *) SDL_malloc(SDL_strlen(arg) + 1);
	if (!newArg) return YES;
	SDL_strlcpy(newArg, arg, SDL_strlen(arg) + 1);
	
	newArgV = (char **) realloc(sdlArgV, sizeof (char *) * (sdlArgC + 2));
	if (!newArgV) {
		SDL_free(newArg);
		return NO;
	}
	sdlArgV = newArgV;
	
	sdlArgC++;
	for (i = sdlArgC; i > pos; i--)
		sdlArgV[i] = sdlArgV[i - 1];
	sdlArgV[pos] = newArg;
	
	return YES;
}

void popArgument() {
	sdlArgC--;
}

int pushArgument(char *parameter) {
	return insertArgument(parameter, sdlArgC);
}

/*
 * NSApplication
 */
@interface SDLApplication : NSApplication
@end

@implementation SDLApplication
- (void)terminate:(id)sender {
    SDL_Event event;
    event.type = SDL_QUIT;
    SDL_PushEvent(&event);
}

- (void)sendEvent:(NSEvent *)event {
	if (([event type] == NSKeyDown) || ([event type] == NSKeyUp)) {
		if(!([event modifierFlags] & NSCommandKeyMask))
			return;
	}
	
	[super sendEvent:event];
}
@end

#ifdef main
#undef main
#endif

/*
 * Main
 */
int main(int argc, const char **argv)
{
	copyArguments(argc, (char **) argv);
	
	/* Restore Finder argument */
	if((sdlArgC == 2) && (strncmp(sdlArgV[1], "-psn", 4) == 0))
		popArgument();
	
    [SDLApplication poseAsClass:[NSApplication class]];
	NSApplicationMain(argc, argv);
	
	return 0;
}
